//
//  Client_RF225_MovRplController.swift
//  Wmsmobile
//
//  Created by xuNick on 16/9/10.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class Client_RF225_MovRplController:  HDFounctionBaseController , HDBarcodeInputCellInputDelegate , HDFounctionBottomViewDelegate , HDSwitchCellDelegate , HDKeyboardInputCellDelegate , HDNumberInputCellDelegate{
    //MARK: - property
    let dataArray:[[String]] = [
        ["区域" , "补货"],
        ["移出货位" , "货品名称" , "规格/批次" , "件数" , "移入货位"],
        ["移出货位","货品条码","件数","移入货位"]
    ]
    var piType : String  = "0"
    var endFlag : Bool = false
    var poToBin : String?
    var poFromBin : String?
    var poArticleCode : String?
    var piQpc : String?
    var piZone: String?
    lazy fileprivate var bottomView:HDFounctionBottomView = {
        let view = HDFounctionBottomView(array: ["移出异常", "移入异常"])
        return view
    }()
    
    //MARK: - lifeCycle
    override func viewDidLoad() {
        self.tableView.register(HDBarcodeInputCell.self, forCellReuseIdentifier: "HDBarcodeInputCell")
        self.tableView.register(HDProductInfocell.self, forCellReuseIdentifier: "HDProductInfocell")
        self.tableView.register(HDKeyboardInputCell.self, forCellReuseIdentifier: "HDKeyboardInputCell")
        self.tableView.register(HDSwitchCell.self, forCellReuseIdentifier: "HDSwitchCell")
        self.tableView.register(HDNumberInputCell.self, forCellReuseIdentifier: "HDNumberInputCell")
        self.tableView.addSubview(self.bottomView)
        self.tableView.contentInset.bottom = bottomView.height
        self.bottomView.delegate = self
        super.viewDidLoad()
    }
    override func viewDidAppear(_ animated: Bool) {
        let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 0)) as! HDKeyboardInputCell
        cell.state = inputViewState.activated
    }
    //MARK: - delegate
    func clicKKeyboardReturn(_ cell: HDKeyboardInputCell) {
        let indexPath = self.tableView.indexPath(for: cell)
        let position = ((indexPath as NSIndexPath?)?.section)! * 100 + ((indexPath as NSIndexPath?)?.row)!
        if position != 202 && cell.codeInputView.textField.text?.characters.count < 1 {
            return
        }
        let celltext = cell.codeInputView.textField.text!
        switch position {
        case 0:
//            public int getRplInfo(
//            int piType,                         // 作业类型，0-补货，1-移库
//            string piAreaCode,                  // 区域号
//            string piOperator,                  // 操作员Code
//            out string poRplNum,                // 补货单号
//            out int poRplLine,                  // 补货单行号
//            out string poFromBin,               // 来源货位
//            out string poToBin,                 // 目标货位
//            out string poTag,                   // 0-整托盘补货，1-整箱拣货
//            out string poArticleCode,           // 货品代码
//            out string poArticleName,     // 货品名称
//            out string poSpec,            // 规格
//            out string poLot,             // 批次
//            out string poQpc,             // 件数
//            out string poErrMsg          
//            )                             // 返回值，0正确，其他错误
            self.getData(["piType" : piType , "piAreaCode" : celltext , "piOperator" : (userInfo?.userName)!], bodyMethod: "getRplInfo", suffix: "330", success: { (dict) in
                //展示数据
                self.piZone = celltext
                self.poToBin = self.downloadData["poToBin"] ?? ""
                self.poFromBin = self.downloadData["poFromBin"] ?? ""
                self.poArticleCode = self.downloadData["poArticleCode"] ?? ""
                for i in 0...4 {
                    let productcell = self.tableView.cellForRow(at: IndexPath(item: i, section: 1)) as? HDProductInfocell
                    switch i {
                    case 0 :
                        productcell?.textField.text = self.downloadData["poFromBin"] ?? ""
                    case 1:
                        productcell?.textField.text = self.downloadData["poArticleName"] ?? ""
                        break
                    case 2:
                        productcell?.textField.text = (self.downloadData["poArticleName"] ?? "") + "/" + (self.downloadData["poLot"] ?? "")
                        break
                    case 3:
                        productcell?.textField.text = self.downloadData["poQpc"] ?? ""
                        break
                    case 4:
                        productcell?.textField.text = self.poToBin
                        break
                    default:
                        break
                    }
                    self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 2))
                }
                }, failed: { _ in 
                   cell.state = inputViewState.wrong
            })
            
            break
           default:
            break
        }
    }
    func clickSwitch(_ isOn: Bool) {
        let cell = self.tableView.cellForRow(at: IndexPath(item: 1, section: 0)) as! HDSwitchCell
        if isOn{ // 打开
            cell.titleView.text = "移库"
            self.piType = "1"
        }else{ //关闭
            cell.titleView.text = "补货"
            self.piType = "0"
        }
    }
    func finishNumInput(_ cell: HDNumberInputCell) {
        if cell.titleView.text == "批号/日期"{
            if Int(cell.boxNumberTextField.text ?? "0") == nil{
                self.showMessage("输入的批号不合法", success: false)
                return
            }
        }
        if cell.titleView.text == "整件/零散" {
            if Int(cell.boxNumberTextField.text ?? "0") == nil{
                self.showMessage("输入的整件数不合法", success: false)
                return
            }
            if Double(cell.bagNumberTextField.text ?? "0.0") == nil{
                self.showMessage("输入的零散数不合法", success: false)
                return
            }
        }
        let indexPath = self.tableView.indexPath(for: cell)
        switch (indexPath! as NSIndexPath).row {
        case 2:
            let celltext = (cell.boxNumberTextField.text ?? "0") + "+" + (cell.bagNumberTextField.text ?? "0")
            self.goNextCell(cell, nextInsexPath: IndexPath(item: 3, section: 2))
            self.piQpc = celltext
            break
        default:
            break
        }
    }
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.bottomView.y = KscreenHeight - bottomView.height + self.tableView.contentOffset.y
    }
    func clickFounctionBottom(_ position: NSInteger) {
        guard piZone != nil else{
            self.showMessage("区域验证成功后再试", success: false)
            return
        }
        var piToBin : String?
        switch position {
        case 0:
//            1.5.1.3.	RF330/RplExcept
//            public int RplExcept(
//            int piType,                           // 0-补货，1-移库
//            string piRplNum,                      // 单号
//            int piRplLine,                        // 行号
//            string piToBin,                       // 目标货位,如果是移出异常，传来源货位，移入异常传目标货位
//            string piOperator,                    // 操作员Code
            //            out string poErrMsg
            //            )                                     // 返回值，0正确，其他错误
            //
            piToBin = self.poFromBin
        case 1:
            piToBin = self.poToBin
            break
        default:
            break
        }
         self.getData(["piType" : piType , "piRplNum" : self.downloadData["poRplNum"]! , "piRplLine" : self.downloadData["poRplLine"]! , "piToBin" : piToBin! , "piOperator" : (userInfo?.userName)!], bodyMethod: "RplExcept", suffix: "330", success: { (dict) in
            self.resetController(self.activedCell!, nextItem: 0, nextSection: 0, message: piToBin == self.poFromBin ? "移出异常成功" : "移入异常成功", success: true)
            }) { _ in 
                self.activedCell?.state = inputViewState.activated
        }
    }
    func clicKReturn(_ cell: HDBarcodeInputCell) {
        let indexpath = self.tableView.indexPath(for: cell)!
        if (indexpath as NSIndexPath).section * 100 + (indexpath as NSIndexPath).row != 202 && cell.codeInputView.textField.text?.characters.count < 1 {
            return
        }
        let celltext = cell.codeInputView.textField.text
        switch (indexpath as NSIndexPath).section * 100 + (indexpath as NSIndexPath).row  {
        case 200:
            if celltext == poFromBin {
                self.goNextCell(cell, nextInsexPath: IndexPath(item: 1, section: 2))
            }else{
                self.showMessage("输入货位有误", success: false)
                cell.state = inputViewState.wrong
            }
          break
        case 201:
            for string in (self.poArticleCode?.components(separatedBy: ",")) ?? [""]{
                if celltext == string{
                    self.oneToManyHandler(string, piOwner: nil, piBin: poFromBin!, success: { (dict) in
                        self.downloadData += dict
                        self.goNextCell(cell, nextInsexPath: IndexPath(item: 2, section: 2))
                        let cellnum = self.tableView.cellForRow(at: IndexPath(item: 2, section: 2)) as! HDNumberInputCell
                        let stringarr = self.downloadData["poQpc"]?.components(separatedBy: "+")
                        cellnum.boxNumberTextField.text = stringarr?.first
                        cellnum.bagNumberTextField.text =  stringarr?.count == 2 ? stringarr?.last : "0"
                        }, failed: { 
                          cell.state = inputViewState.wrong
                    })
                    return
                }
            }
            self.showMessage("条码输入有误", success: false)
            break
        case 203:
            if celltext == poToBin{
//                1.5.1.2.	RF325/updRpl
//                public int updRpl(
//                int piType,                     // 0-补货，1-移库
//                string piRplNum,                // 单号
//                int piRplLine,                  // 行号
//                string piFromBin,               // 来源货位
//                string piToBin,                 // 目标货位
//                string piArticle,               // 货品Gid
//                string piQpc,                   // 件数
//                string piOperator,              // 操作员Code
//                out string poErrMsg
//                )                               // 返回值，0正确，其他错误

                self.getData(["piType" : piType , "piRplNum" : self.downloadData["poRplNum"]! , "piRplLine" : self.downloadData["poRplLine"]! , "piFromBin" : poFromBin! , "piToBin" : poToBin! ,"piArticle" : self.downloadData["内码"]! ,"piQpc" :  piQpc! , "piOperator" : (userInfo?.userName)!], bodyMethod: "updRpl", suffix: nil, success: { (dict) in
                    let msg = self.piType == "0" ? "补货成功" : "移库成功"
                    self.resetController(cell, nextItem: 0, nextSection: 0, message: msg, success: true)
                    }, failed: { _ in 
                        cell.state = inputViewState.wrong
                })
            }else{
                self.showMessage("输入的货位有误", success: false)
            }
            break
        default:
            break
        }
        
    }
    //MARK: - private
    override func isEmpty() -> (Bool) {
        if let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 1)) as? HDProductInfocell{
            if cell.textField.text?.characters.count > 0 {
                return false
            }else{
                return true
            }
        }else{
            return false
        }
    }
    //MARK: - tableviewDatasource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray[section].count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellOriginal:HDFounctionBaseCell?
        switch ((indexPath as NSIndexPath).section) * 100 + ((indexPath as NSIndexPath).row) {
        case 0:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDKeyboardInputCell") as! HDKeyboardInputCell
            let cell = cellOriginal as! HDKeyboardInputCell
            cell.InputDelegate = self
            
        case 200,201,203:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.InputDelegate = self
            
        case 101...104:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
        case 202:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDNumberInputCell") as! HDNumberInputCell
            let cell = cellOriginal as! HDNumberInputCell
            cell.precisionBox = 0
            cell.precisionBag = 2
            cell.delegate = self
        case 1:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDSwitchCell") as! HDSwitchCell
            let cell = cellOriginal as! HDSwitchCell
            cell.delegate = self
            let string = self.piType == "0" ? "补货" : "移库"
            cell.titleView.text = string
            return cell
        default:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
        }
        if !self.reuseFlag {
            cellOriginal?.clearContent()
        }
        cellOriginal!.titleView.text = dataArray[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
        return cellOriginal!
    }
    //MARK: - tableViewDelegate
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 2:
            return UIView(frame: CGRect(x: 0, y: 0, width: KscreenWidth, height: 0.1))
        default:
            return nil
        }
    }
}
